class ByteQueue {
    constructor(maxSize = 100) {
        // 队列最大容量
        this.maxSize = maxSize;
        
        // 初始化队列
        this.queue = [];
        
        // 队列当前大小
        this.size = 0;
        
        // 队列头部索引
        this.head = 0;
        
        // 队列尾部索引
        this.tail = 0;
    }

    // 将数据放入队列
    put(data) {
        // 检查数据类型
        if (!Buffer.isBuffer(data)) {
            data = Buffer.from(data);
        }

        // 检查队列是否已满
        if (this.size >= this.maxSize) {
            throw new Error('Queue is full');
        }

        // 将数据放入队列
        this.queue[this.tail] = data;
        this.tail = (this.tail + 1) % this.maxSize;
        this.size++;

        return true;
    }

    // 从队列中取出数据
    take() {
        // 检查队列是否为空
        if (this.size === 0) {
            return null;
        }

        // 取出数据
        const data = this.queue[this.head];
        this.queue[this.head] = null;
        this.head = (this.head + 1) % this.maxSize;
        this.size--;

        return data;
    }

    // 查看队列头部数据（不取出）
    peek() {
        // 检查队列是否为空
        if (this.size === 0) {
            return null;
        }

        return this.queue[this.head];
    }

    // 获取队列当前大小
    getSize() {
        return this.size;
    }

    // 检查队列是否为空
    isEmpty() {
        return this.size === 0;
    }

    // 检查队列是否已满
    isFull() {
        return this.size >= this.maxSize;
    }

    // 清空队列
    clear() {
        this.queue = [];
        this.size = 0;
        this.head = 0;
        this.tail = 0;
    }

    // 获取队列中所有数据的拷贝
    toArray() {
        const result = [];
        let current = this.head;
        
        for (let i = 0; i < this.size; i++) {
            result.push(Buffer.from(this.queue[current]));
            current = (current + 1) % this.maxSize;
        }
        
        return result;
    }

    // 将多个数据包合并为一个Buffer
    concatenate() {
        if (this.size === 0) {
            return Buffer.alloc(0);
        }

        return Buffer.concat(this.toArray());
    }

    // 查找特定字节序列
    find(pattern) {
        if (!Buffer.isBuffer(pattern)) {
            pattern = Buffer.from(pattern);
        }

        const concatenated = this.concatenate();
        
        for (let i = 0; i <= concatenated.length - pattern.length; i++) {
            let found = true;
            for (let j = 0; j < pattern.length; j++) {
                if (concatenated[i + j] !== pattern[j]) {
                    found = false;
                    break;
                }
            }
            if (found) {
                return i;
            }
        }
        
        return -1;
    }

    // 获取队列统计信息
    getStats() {
        return {
            size: this.size,
            maxSize: this.maxSize,
            head: this.head,
            tail: this.tail,
            isEmpty: this.isEmpty(),
            isFull: this.isFull()
        };
    }
}

module.exports = { ByteQueue };
